'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

// 根据路径获取对象的值
function getPathValue(path = '', sourceData = {}, df = '') {
    return path.split('.').reduce((source, key) => {
        return source[key] || df;
    }, sourceData);
}

// 字符串格式化
function formatString(char, sourceData = {}) {
    return (
        char &&
        char.replace &&
        char.replace(/\{(.*?)\}/g, (_, index) => {
            return getPathValue(index, sourceData);
        })
    );
}

class Translator {
    static state = { $lang: 'zh' };
    static langData = {};
    static mthodsMap = {
        Single: Translator.createSingle,
        Nesting: Translator.createNesting,
        Auto: Translator.createAuto
    };

    // 核心方法, 只获取数据不格式化
    static createTranslate(category = 'Auto', data = Translator.langData) {
        if (Object.keys(Translator.mthodsMap).indexOf(category) === -1) {
            throw new Error(category + ' is not defined');
        }

        const result = Translator.mthodsMap[category](data);
        if (!Translator.$t()) Translator.$t = result;
        return result;
    }

    static createSingle(data) {
        return text => data[Translator.state.$lang][text];
    }
    static createNesting(data) {
        return text => getPathValue(text, data[Translator.state.$lang]);
    }
    static createAuto(data) {
        return text =>
            text.indexOf('.') >= 0
                ? Translator.createNesting(data)(text)
                : Translator.createSingle(data)(text);
    }

    static $t() {
        return false;
    }

    /* 与Vue集成 */
    static mergeVue(state) {
        Translator.state = state;
    }
    /* 增加语言数据 */
    static addData(subData = {}) {
        const keys = Array.from(
            new Set([
                ...Object.keys(Translator.langData),
                ...Object.keys(subData)
            ])
        );
        const newLangData = {};
        keys.forEach(key => {
            newLangData[key] = {
                ...Translator.langData[key],
                ...subData[key]
            };
        });
        Translator.langData = newLangData;
    }
    /* 集成element-i8n */
    static mergeElementUI(path, options = {}) {
        const key = getPathValue(
            path,
            Translator.langData[Translator.state.$lang]
        );
        return formatString(key, options);
    }
}

const rawOptions = {
    keyLevel: 'Auto',
    lang: 'zh',
    langData: undefined
};

Translator.install = function(Vue, options = {}) {
    options = { ...rawOptions, ...options };
    if (Vue.version[0] === '2') {
        Vue.prototype.$t = Translator.createTranslate(options.keyLevel);
        Vue.$data.$lang = options.lang || Translator.state.$lang;
    } else {
        Translator.addData(options.langData);
        Vue.config.globalProperties.$t = Translator.createTranslate(
            options.keyLevel
        );
    }
};

exports.default = Translator;
